package com.handinglian.ai.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.handinglian.ai.common.util.FastJsonUtil;
import com.handinglian.ai.system.dto.MenuDto;
import com.handinglian.ai.system.dto.PermissionDto;
import com.handinglian.ai.system.entity.Menu;
import com.handinglian.ai.system.mapper.MenuMapper;
import com.handinglian.ai.system.service.MenuService;
import com.handinglian.ai.system.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service("menuService")
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private PermissionService permissionService;

    @Override
    public List<MenuDto> list() {
        List<PermissionDto> permissionDtos = permissionService.list();
        List<MenuDto> menuOneLevelDto = listByParentId(CollUtil.newArrayList(0), permissionDtos);
        List<Integer> menuIds = menuOneLevelDto.stream().map(menuDto -> menuDto.getId()).collect(Collectors.toList());

        updateMenuDto(menuIds, menuOneLevelDto, permissionDtos);
        return menuOneLevelDto;
    }

    private void updateMenuDto(List<Integer> parentIds, List<MenuDto> parentMenuDto, List<PermissionDto> permissionDtos){
        List<MenuDto> menuDtos = listByParentId(parentIds, permissionDtos);
        List<Integer> menuIds = menuDtos.stream().map(menuDto -> menuDto.getId()).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(menuIds)){
            for (MenuDto menuDto : parentMenuDto){
                for (MenuDto menuSubDto : menuDtos){
                    if (menuDto.getId().equals(menuSubDto.getParentId())){
                        menuDto.addMenu(menuSubDto);
                    }
                }
            }
            updateMenuDto(menuIds, menuDtos, permissionDtos);
        }
    }

    public List<MenuDto> listByParentId(List<Integer> parentIds, List<PermissionDto> permissionDtos) {
        List<Menu> menuList = menuMapper.findByParentIdIn(parentIds);
        List<MenuDto> menuDtos = FastJsonUtil.ListToList(menuList, MenuDto.class);

        menuDtos.forEach(menuDto -> {
            permissionDtos.forEach(permissionDto -> {
                if (permissionDto.getMenuId().equals(menuDto.getId())){
                    menuDto.getPermissionDtos().add(permissionDto);
                }
            });
        });
        return menuDtos;
    }
}
